package com.example.javamaday.leetcode;

import com.example.javamaday.leetcode.base.ListNode;

public class LeetCodeTest0142 {

    public static void main(String[] args) {

    }

    private ListNode fastNode;
    private ListNode slowNode;
    private ListNode resultNode;

    public ListNode detectCycle(ListNode head) {
        if (hasCycle(head)) {
            resultNode = head;
            while (true) {
                if (resultNode == slowNode) {
                    return resultNode;
                } else {
                    resultNode = resultNode.next;
                    slowNode = slowNode.next;
                }
            }
        } else {
            return null;
        }
    }

    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        fastNode = head;
        slowNode = head;
        while (fastNode != null && slowNode != null) {
            if (fastNode.next != null) {
                fastNode = fastNode.next.next;
                slowNode = slowNode.next;
                if (fastNode != null && slowNode != null && fastNode == slowNode) {
                    return true;
                }
            } else {
                return false;
            }
        }
        return false;
    }
}
